package com.zhangc.blog.admin.web.controller.admin;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangc.blog.admin.entity.BlogInfoEntity;
import com.zhangc.blog.admin.entity.BlogTagRelationEntity;
import com.zhangc.blog.admin.service.BlogInfoServiceImpl;
import com.zhangc.blog.admin.service.BlogTagRelationServiceImpl;
import com.zhangc.blog.admin.web.dto.AjaxPutPage;
import com.zhangc.blog.admin.web.dto.AjaxResultPage;
import com.zhangc.blog.admin.web.security.CurrentUser;
import com.zhangc.blog.admin.web.security.UserPrincipal;
import com.zhangc.blog.base.ResultBO;
import com.zhangc.blog.base.enums.DeleteStatusEnum;
import com.zhangc.blog.base.utils.FileUtils;

/**
 * 功能描述:<br>
 *
 * @author wx:fdzhangc
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/admin/v1/blog")
public class BlogV1Controller {
    @Autowired
    private BlogInfoServiceImpl blogInfoService;
    @Autowired
    private BlogTagRelationServiceImpl blogTagRelationService;

    /**
     * 跳转博客编辑界面
     *
     * @return java.lang.String
     * @date 2019/8/28 15:03
     */
    @GetMapping("/edit")
    public ModelAndView gotoBlogEdit(@RequestParam(required = false) Long blogId) {
        ModelAndView mv = new ModelAndView();
        if (blogId != null) {
            BlogInfoEntity blogInfo = blogInfoService.getById(blogId);
            List<BlogTagRelationEntity> list = blogTagRelationService.list(
                    new QueryWrapper<BlogTagRelationEntity>()
                            .lambda()
                            .eq(BlogTagRelationEntity::getBlogId, blogId)
            );
            List<Integer> tags = null;
            if (!CollectionUtils.isEmpty(list)) {
                tags = list.stream().map(
                        BlogTagRelationEntity::getTagId)
                        .collect(Collectors.toList());
            }
            mv.addObject("blogTags", tags);
            mv.addObject("blogInfo", blogInfo);
        }
        mv.setViewName("adminLayui/blog-edit");
        return mv;
    }

    /**
     * 跳转博客列表界面
     *
     * @return java.lang.String
     * @date 2019/8/28 15:20
     */
    @GetMapping("/bloglist")
    public String gotoBlogList() {
        return "adminLayui/blog-list";
    }

    /**
     * 保存文章图片
     *
     * @param request
     * @param file
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2019/8/26 13:57
     */
    @ResponseBody
    @PostMapping("/uploadFile")
    public Map<String, Object> uploadFileByEditormd(HttpServletRequest request,
            @RequestParam(name = "editormd-image-file") MultipartFile file) throws
            URISyntaxException {
        String suffixName = FileUtils.getSuffixName(file);
        //生成文件名称通用方法
        String newFileName = FileUtils.getNewFileName(suffixName);
        File fileDirectory = new File(FileUtils.FILE_UPLOAD_DIC);
        //创建文件
        File destFile = new File(FileUtils.FILE_UPLOAD_DIC + newFileName);
        Map<String, Object> result = new HashMap<>();
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdirs()) {
                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            String fileUrl = FileUtils.FILE_SQL_DIC + newFileName;
            result.put("success", 1);
            result.put("message", "上传成功");
            result.put("url", fileUrl);
        } catch (IOException e) {
            result.put("success", 0);
        }
        return result;
    }

    /**
     * 保存文章内容
     *
     * @param blogTagIds
     * @param blogInfo
     * @return com.zhulin.blog.dto.Result
     * @date 2019/8/28 15:04
     */
    @ResponseBody
    @PostMapping("/edit")
    public ResultBO<String> saveBlog(@RequestParam("blogTagIds[]") List<Integer> blogTagIds, BlogInfoEntity blogInfo) {
        if (CollectionUtils.isEmpty(blogTagIds) || ObjectUtils.isEmpty(blogInfo)) {
            return ResultBO.errorParam();
        }
        blogInfo.setCreateTime(new Date());
        blogInfo.setUpdateTime(new Date());
        if (blogInfoService.saveOrUpdate(blogInfo)) {
            blogTagRelationService.removeAndsaveBatch(blogTagIds, blogInfo);
            return ResultBO.of(blogInfo.getBlogId().toString());
        }
        return ResultBO.error500(null);
    }

    /**
     * 文章分页列表
     *
     * @param ajaxPutPage 分页参数
     * @param condition   筛选条件
     * @return com.site.blog.pojo.dto.AjaxResultPage<com.site.blog.entity.BlogInfo>
     * @date 2019/8/28 16:43
     */
    @ResponseBody
    @GetMapping("/list")
    public AjaxResultPage<BlogInfoEntity> getContractList(AjaxPutPage<BlogInfoEntity> ajaxPutPage, BlogInfoEntity condition) {
        LambdaQueryWrapper<BlogInfoEntity> queryWrapper = Wrappers.<BlogInfoEntity>lambdaQuery()
                //id
                .eq(Objects.nonNull(condition.getBlogId()), BlogInfoEntity::getBlogId, condition.getBlogId())
                //id
                .eq(Objects.nonNull(condition.getBlogCategoryId()), BlogInfoEntity::getBlogCategoryId, condition.getBlogCategoryId())
                //标题查询
                .like(Objects.nonNull(condition.getBlogTitle()), BlogInfoEntity::getBlogTitle, condition.getBlogTitle());
        queryWrapper.orderByDesc(BlogInfoEntity::getCreateTime);
        Page<BlogInfoEntity> page = ajaxPutPage.putPageToPage();
        blogInfoService.page(page, queryWrapper);
        AjaxResultPage<BlogInfoEntity> result = new AjaxResultPage<>();
        result.setData(page.getRecords());
        result.setCount(page.getTotal());
        return result;
    }

    /**
     * 修改博客的部分状态相关信息
     *
     * @param blogInfo
     * @return com.site.blog.pojo.dto.Result
     * @date 2019/8/29 12:22
     */
    @ResponseBody
    @PostMapping("/blogStatus")
    public ResultBO<String> updateBlogStatus(BlogInfoEntity blogInfo) {
        blogInfo.setUpdateTime(new Date());
        boolean flag = blogInfoService.updateById(blogInfo);
        if (flag) {
            return ResultBO.success();
        }
        return ResultBO.error500(null);
    }

    /**
     * 修改文章的删除状态为已删除
     *
     * @param blogId
     * @return com.site.blog.pojo.dto.Result
     * @date 2019/8/29 14:02
     */
    @ResponseBody
    @PostMapping("/delete")
    public ResultBO<String> deleteBlog(@RequestParam Long blogId, @CurrentUser UserPrincipal user) {
        BlogInfoEntity blogInfo = new BlogInfoEntity()
                .setBlogId(blogId)
                .setIsDeleted(DeleteStatusEnum.DELETED.getStatus())
                .setUpdateTime(new Date());
        boolean flag = blogInfoService.updateById(blogInfo);
        if (flag) {
            return ResultBO.success();
        }
        return ResultBO.error500(null);
    }

    /**
     * 清除文章
     *
     * @param blogId
     * @return com.site.blog.pojo.dto.Result
     * @date 2019/8/29 14:02
     */
    @ResponseBody
    @PostMapping("/clear")
    public ResultBO<String> clearBlog(@RequestParam Long blogId) {
        if (blogInfoService.clearBlogInfo(blogId)) {
            return ResultBO.success();
        }
        return ResultBO.error500(null);
    }

    /**
     * 还原文章
     *
     * @param blogId
     * @return com.site.blog.pojo.dto.Result
     * @date 2019/8/29 16:36
     */
    @ResponseBody
    @PostMapping("/restore")
    public ResultBO<String> restoreBlog(@RequestParam Long blogId) {
        BlogInfoEntity blogInfo = new BlogInfoEntity()
                .setBlogId(blogId)
                .setIsDeleted(DeleteStatusEnum.NO_DELETED.getStatus())
                .setUpdateTime(new Date());
        boolean flag = blogInfoService.updateById(blogInfo);
        if (flag) {
            return ResultBO.success();
        }
        return ResultBO.error500(null);
    }

    @ResponseBody
    @GetMapping("/select")
    public List<BlogInfoEntity> getBlogInfoSelect() {
        return blogInfoService.list();
    }

}
